import React, { Component } from 'react'
import { StatusBar, DeviceEventEmitter, FlatList, WebView, Modal, Alert, RefreshControl, TouchableOpacity, Image, Text, ActivityIndicator, BackHandler, ScrollView, View} from 'react-native'
import Button from '../Components/Button'
import { Rating } from 'react-native-elements'
import { connect } from 'react-redux'
import TimerMixin from 'react-timer-mixin'
import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain
import ServerList from '../Components/ServerList'
import OrderDetailActions from '../Redux/OrderDetailRedux'

// Styles
import styles from './Styles/OrderDetailScreenStyle'

class OrderDetailScreen extends Component {
  mixins: [TimerMixin]
  static navigationOptions = {
    title: '订单详情'
  }
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    this.state = {
      id: state.params.id,
      refreshing: false,
      modalVisible: true,
      chooseServerModal: true,
      lastTime: null,
      status: null,
      serverList: null,
    }
  }
  componentWillMount() {
    DeviceEventEmitter.addListener('refreshOrderDetail', (e)=>this.props.getOrder(this.state.id, this.props.token))
  }
  componentDidMount() {
    this.props.getOrder(this.state.id, this.props.token)
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.order.payload
      && this.props.order.payload
      && prevProps.order.payload.id === this.props.order.payload.id
      && prevProps.order.payload.status !== this.props.order.payload.status) {
      DeviceEventEmitter.emit('refreshOrderList',  {})
    }
    if(prevProps.order.fetching
      && !this.props.order.fetching
      && this.props.order.payload) {
      /** update order status **/
      this.setState({status: this.props.order.payload.status})
      if (this.props.order.payload.status == 'success') {
        this.getServerList()
        this.timer = setInterval(() => this.getServerList(), 5000)
      } else {
        clearInterval(this.timer)
      }
      /** if status eq connected **/
      if (this.props.order.payload.status == 'connected') {
        this.updateOrderTimer = setTimeout(()=>this.props.getOrder(this.state.id, this.props.token), 10000)
      } else {
        clearTimeout(this.updateOrderTimer)
      }
    }
    if(prevProps.order.fetching
      && prevState.refreshing
      && !this.props.order.error) {
      this.setState({refreshing:false})
    }
    if(prevProps.order.fetching
      && !this.props.fetching
      && prevState.modalVisible) {
      this.setState({modalVisible:false})
    }
    if(prevProps.order.deleteFetching
      && !this.props.deleteFetching
      && prevState.modalVisible) {
      this.setState({modalVisible:false})
      this.props.navigation.goBack()
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer)
    clearTimeout(this.updateOrderTimer)
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  startServer() {
    clearTimeout(this.updateOrderTimer)
    let url = domain+'/api/user/order_operate'
    return fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token
      },
      body: JSON.stringify({
        id: this.state.id,
        status: 'serving'
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        this.props.getOrder(this.state.id, this.props.token)
      }).catch((error) => Alert.alert('操作失败'))
  }
  endServer() {
    let url = domain+'/api/user/order_operate'
    return fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token
      },
      body: JSON.stringify({
        id: this.state.id,
        status: 'complete'
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        this.props.getOrder(this.state.id, this.props.token)
      }).catch((error) => Alert.alert('操作失败'))
  }
  chooseServer(uid) {
    clearInterval(this.timer)
    this.setState({modalVisible:true})
    let url = domain+'/api/order/confirm'
    return fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token
      },
      body: JSON.stringify({
        id: this.state.id,
        uid: uid
      })
      }).then((response) => response.json())
      .then((responseJson) => {
        this.props.getOrder(this.state.id, this.props.token)
        //this.setState({serverModalVisible:false})
      }).catch((error) => {
      })
  }
  getServerList() {
    let url = domain+'/api/order/single'
    return fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token
      },
      body: JSON.stringify({
        id: this.state.id
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        this.setState({serverList:responseJson.data})
      }).catch((error) => console.warn(error))
  }
  _goPay = () => {
    this.props.navigation.navigate('PayScreen',{
      id:this.state.id,money:this.props.order.payload.order_amount})
  }
  _onRefresh() {
    this.setState({refreshing:true})
    this.props.getOrder(this.state.id, this.props.token)
  }
  _onCancel = () => {
    Alert.alert('提醒', '确定取消此订单?', [
      {text:'确认',onPress:()=>{
        this.setState({modalVisible:true})
        this.props.cancelOrder(this.state.id,this.props.token)
      }},
      {text:'不',onPress:()=>null}
    ], {cancelable:false})
  }
  _onDelete = () => {
    Alert.alert('提醒', '确定删除此订单?', [
      {text:'确认',onPress:()=>{
        this.setState({modalVisible:true})
        this.props.deleteOrder(this.state.id,this.props.token)
      }},
      {text:'取消',onPress:()=>null}
    ], {cancelable:false})
  }
  _start = () => {
    /** start service **/
    var duration = this.props.order.payload.detail[0].clock
    this.setState({lastTime:duration})

    /** for test **/
    this.setState({status:'serving'})

    this.timer = setInterval(()=>{
      var lastTime = this.state.lastTime
      if (--lastTime <= 0) {
        /** service over **/
        clearInterval(this.timer)
        /** for test **/
        this.setState({status:'complete'})
      }
      this.setState({lastTime: lastTime})
    }, 6000)
  }
  getLoadingView() {
    return (
      <Modal
        transparent={true}
        visible={this.state.modalVisible}
        onRequestClose={()=>null}>
        <View style={styles.loadingModal}>
          <View style={styles.loadingModalContainer}>
            <ActivityIndicator color='rgba(255,255,255,0.85)' />
            <Text style={styles.loadingModalTitle}>请稍后...</Text>
          </View>
        </View>
      </Modal>
    )
  }
  render () {
    let mainView = null
    if (this.props.order.error) {
      mainView = <View><Text>ERROR</Text></View>
    } else if (!this.props.order.payload) {
    } else {
      const order = this.props.order.payload
      const { navigate, goBack } = this.props.navigation
      mainView = (
        <ScrollView
          refreshControl={
            <RefreshControl
              refreshing={this.state.refreshing}
              onRefresh={this._onRefresh.bind(this)}
            />
          }
          style={styles.container}>
          {['connected','start'].some((item) => item === this.state.status) &&
            <View style={{height:220,marginTop:-10,marginBottom:-30,overflow:'hidden'}}>
              <WebView
                source={{uri:`http://m.amap.com/navi/?start=${order.artificer.longx},${order.artificer.laty}&dest=${order.longitude},${order.latitude}&destName=我的位置&naviBy=car&key=570267aa7ecb5f492b9b0e757e31c777`}}
                style={{marginTop:-55,marginBottom:-80}}/>
            </View>
          }
          <View style={styles.bigSection}>
            <Text style={{fontSize:16,color:'rgba(0,0,0,0.85)'}}>{order.order_status}</Text>
            {this.state.status === 'success' &&
              <Text>正在等待师傅接单...</Text>
            }
            {this.state.status === 'serving' && (
              <View style={{marginTop:5}}>
                <Text>开始时间:  {order.start_time}</Text>
                <Text>结束时间:  {order.end_time}</Text>
              </View>
            )}
            {this.state.status === 'serving0' && (
              <View style={{alignItems:'center'}}>
                <Text style={{fontSize:30,color:'#EDD834'}}>{this.state.lastTime}</Text>
                <Text style={{fontSize:12,color:'rgba(0,0,0,0.38)'}}>服务完成倒计时(分钟) </Text>
              </View>
            )}
          </View>
          {order.artificer != '' &&
            <TouchableOpacity
              style={styles.server}
              onPress={()=>navigate('ServerDetailScreen',{id:order.artificer.id})}>
              <Image
                style={styles.avatar}
                source={{uri:order.artificer.img}} />
              <Text>{order.artificer.name}</Text>
            </TouchableOpacity>
          }
          <TouchableOpacity
            style={styles.commodity}
            onPress={()=>navigate('CommodityDetailScreen',{id:order.detail[0].project_id})}>
            <Image
              style={styles.image}
              source={{uri:order.detail[0].img}} />
            <View>
              <Text style={styles.title}>{order.detail[0].name}</Text>
              <Text style={{fontSize:12}}>价格: <Text style={{color:'#F24D16'}}>{order.detail[0].price}元</Text></Text>
              <Text style={{fontSize:12}}>时长: <Text style={{color:'#F24D16'}}>{order.detail[0].clock}分钟</Text></Text>
            </View>
          </TouchableOpacity>
          <View style={[styles.bigSection, {marginBottom:0,alignItems:'flex-start'}]}>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>总价格: </Text>
              {order.total_amount}</Text>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>优惠券: </Text>
              {order.coupon_price}</Text>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>实际支付: </Text>
              {order.order_amount}</Text>
          </View>
          <View style={[styles.bigSection, {alignItems:'flex-start'}]}>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>预约地址: </Text>
              {order.area} {order.address}</Text>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>联系电话: </Text>
              {order.mobile_phone}</Text>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>订单编号: </Text>
              {order.order_sn}</Text>
            <Text><Text style={{color:'rgba(0,0,0,0.7)'}}>创建时间: </Text>
              {order.create_time}</Text>
          </View>
          <View style={{padding:20}}>
            {this.state.status === 'success' &&
                <Button title='选择师傅' onPress={()=>this.setState({chooseServerModal:true})} />
            }
            {this.state.status === 'requested' && (
              <View>
                <Button margin title='支付' onPress={this._goPay} />
                <Button secondary title='取消订单' onPress={this._onCancel} />
              </View>
            )}
            {this.state.status === 'connected' && (
              <Button title='服务开始' onPress={()=>this.startServer()} />
            )}
            {this.state.status === 'serving' &&
                <Button title='服务完成' onPress={()=>this.endServer()} />
            }
            {this.state.status === 'complete' && order.is_comment == 0 &&
                <View>
                  <Button margin title='评价'
                    onPress={()=>navigate('EvaluationScreen',{id:order.id})} />
                </View>
            }
            {['complete', 'refund_completed', 'canceled'].some((item) => item === this.state.status) &&
              <Button danger title='删除' onPress={this._onDelete} />
            }
          </View>
        </ScrollView>
      )
    }
    return (
      <View style={{flex:1}}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        {mainView}
        {this.state.status === 'success' &&
            <Modal transparent visible={this.state.chooseServerModal} onRequestClose={()=>null}>
              <View style={{flex:1,backgroundColor:'rgba(0,0,0,0.4)',alignItems:'center',justifyContent:'center'}}>
                <View style={{width:'90%',height:'90%',backgroundColor:'white',borderRadius:5,padding:20}}>
                  <View
                    style={{borderColor:'rgba(0,0,0,0.38)',borderBottomWidth:1,paddingBottom:10,marginBottom:20}}>
                    <Text
                      style={{textAlign:'center',fontSize:18,color:'rgba(0,0,0,0.85)'}}>请选择技师</Text>
                    <TouchableOpacity
                      style={{position:'absolute',right:0,top:2}}
                      onPress={()=>this.setState({chooseServerModal:false})}>
                      <Text>关闭</Text>
                    </TouchableOpacity>
                  </View>
                  <View>
                    <FlatList
                      data={this.state.serverList}
                      keyExtractor={(item,index)=>index}
                      renderItem={({item}) =>
                          <View style={{flex:1,flexDirection:'row',alignItems:'center',padding:5}}>
                            <Image
                              style={{width:46,height:46,borderRadius:23,marginRight:10}}
                              source={{uri:item.head_img}} />
                            <View style={{flex:1}}>
                              <View style={{marginBottom:5,flexDirection:'row',alignItems:'center'}}>
                                <Text style={{fontSize:16,color:'rgba(0,0,0,0.85)',marginRight:5}}>{item.nickname}</Text>
                                <Text style={{fontSize:14,color:'#F24D16',marginRight:5}}>{item.sex == 1 ? '男' : '女'}</Text>
                                <Rating imageSize={14} startingValue={parseInt(item.star)} />
                              </View>
                              <Text style={{fontSize:12}}>{item.desc}</Text>
                            </View>
                            <Button title='选择'
                              onPress={()=>this.chooseServer(item.id)} />
                          </View>
                      }/>
                  </View>
                </View>
              </View>
            </Modal>
        }
        {this.getLoadingView()}
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    server: state.server.payload,
    token: state.user.payload.token,
    order: state.orderDetail,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getOrder:(id,token) => dispatch(OrderDetailActions.orderDetailRequest(id,token)),
    cancelOrder:(id,token)=>dispatch(OrderDetailActions.cancelRequest(id,token)),
    deleteOrder:(id,token)=>dispatch(OrderDetailActions.orderDeleteRequest(id,token))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(OrderDetailScreen)
